package com.hy.controller;

import com.hy.AppHttpCodeEnum;
import com.hy.Result.ResponseResult;
import com.hy.appMedicine.dto.MedicineQueryDTO;
import com.hy.medicine.MedicineStockRecord;
import com.hy.service.MedicineService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 药品信息
 */

@Slf4j
@RestController
@RequestMapping("/api/medicine")
@CrossOrigin  // 添加跨域注解
public class MedicineController {

    @Autowired
    private MedicineService medicineService;


    /**
     * 获取药品分类列表
     */
    @GetMapping("/categories")
    public ResponseResult getCategories() {
        return medicineService.getCategories();
    }

    /**
     * 获取药品列表
     */
    @PostMapping("/list")
    public ResponseResult getMedicineList(@RequestBody MedicineQueryDTO queryDTO) {
        return medicineService.getMedicineList(queryDTO);
    }

    // 获取药品详情 - 保持GET，使用路径参数
    @GetMapping("/detail/{id}")
    public ResponseResult getMedicineDetail(@PathVariable Integer id) {
        return ResponseResult.okResult(medicineService.getMedicineDetail(id));
    }

    // 获取药品评价 - 保持GET，使用路径参数
    @GetMapping("/evaluations/{medicineId}")
    public ResponseResult getMedicineEvaluations(@PathVariable Integer medicineId) {
        return ResponseResult.okResult(medicineService.getMedicineEvaluations(medicineId));
    }

    // 获取药品库存 - 保持GET，使用路径参数
    @GetMapping("/stock/{medicineId}")
    public ResponseResult getMedicineStock(@PathVariable Integer medicineId) {
        return ResponseResult.okResult(medicineService.getMedicineStock(medicineId));
    }

    // 更新药品库存 - 保持POST，使用请求体
    @PostMapping("/stock/update")
    public ResponseResult updateMedicineStock(@RequestBody MedicineStockRecord record) {
        try {
            medicineService.updateMedicineStock(record);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(), "库存更新成功");
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR.getCode(), e.getMessage());
        }
    }



    /**
     * 检查药品库存
     * @param medicineId 药品ID
     * @param quantity 需要的数量
     * @return 库存是否充足
     */
    @GetMapping("/checkStock")
    public ResponseResult<Boolean> checkStock(
            @RequestParam("medicineId") Integer medicineId,
            @RequestParam("quantity") Integer quantity) {
        boolean isEnough = medicineService.checkStock(medicineId, quantity);
        return ResponseResult.okResult(isEnough);
    }

}
